/*
 * Test if the ciruit of drv8833 module could control the motor
 * rotate forward and reverse. 
 * 
 * 2019-4-6
 */

#define P_IN1_A 3  //pin IN 1, Group A
#define P_IN2_A 5  //pin IN 2, Group A
#define P_ULT_A 4  //pin nFault, Group A

#define P_IN1_B 6  //pin IN 1, Group B
#define P_IN2_B 9  //pin IN 2, Group B
#define P_ULT_B 7  //pin nFault, Group B

void setup(){
  Serial.begin(115200);
}

void loop(){
  Serial.println("==========");
  Serial.println("Forward.");
  forward(P_IN1_A, P_IN2_A, 100);
  forward(P_IN1_B, P_IN2_B, 200);

  delay(2000);

  Serial.println("Reverse.");
  reverse(P_IN1_A, P_IN2_A, 100);
  reverse(P_IN1_B, P_IN2_B, 200);
  
  delay(2000);

  Serial.println("Brake");
  brake(P_IN1_A, P_IN2_A);
  brake(P_IN1_B, P_IN2_B);
  delay(3000);
}

/* Description:
 *    motor forward.
 * Para:
 *    In_1: drv8833 IN1 Pin
 *    In_2: drv8833 IN2 Pin
 *    spd: speed, Arduino pwm value, range 0-255.
 */
void forward(int In_1, int In_2, int spd){
  analogWrite(In_1, spd);
  digitalWrite(In_2, LOW);
}

/* Description:
 *    motor reverse.
 * Para:
 *    In_1: drv8833 IN1 Pin
 *    In_2: drv8833 IN2 Pin
 *    spd: speed, Arduino pwm value, range 0-255.
 */
void reverse(int In_1, int In_2, int spd){
  digitalWrite(In_1, LOW);
  analogWrite(In_2, spd);
}

/* Description:
 *    Brake the motor, corresponse to the slow decay in the 
 *    datasheet. This indicates short circuit the motor,
 *    thus the motor would be hard to be rotate.
 * Para:
 *    In_1: drv8833 IN1 Pin
 *    In_2: drv8833 IN2 Pin
 */
void brake(int In_1, int In_2){
  digitalWrite(In_1, HIGH);
  digitalWrite(In_2, HIGH);
}

